<template>
  <div class='main'>
    <div id="div1"></div>
  </div>
</template>

<script>
export default {
  mounted() {
    var div1 = document.getElementById('div1')
    let oL,oT
    //限制最大宽高，不让滑块出去
    var maxW = document.body.clientWidth - div1.offsetWidth;
    var maxH = 40
    //手指触摸开始，记录div的初始位置
    div1.addEventListener("touchstart", function(e) {
      var ev = e || window.event;
      var touch = ev.targetTouches[0];
      // oL = touch.clientX - div1.offsetLeft;
      oT = touch.clientY - div1.offsetTop;
      document.addEventListener("touchmove", defaultEvent, { passive: false });
    },{ passive: false });
    //触摸中的，位置记录
    div1.addEventListener("touchmove", function(e) {
      var ev = e || window.event;
      var touch = ev.targetTouches[0];
      // var oLeft = touch.clientX - oL;
      var oTop = touch.clientY - oT;
      // if (oLeft < 0) {
      //   oLeft = 0;
      // } else if (oLeft >= maxW) {
      //   oLeft = maxW;
      // }
      if (oTop < 0) {
        oTop = 0;
      } else if (oTop >= maxH) {
        oTop = maxH;
      }
      // div1.style.left = oLeft + "px";
      div1.style.top = oTop + "px";
    },{ passive: false });
    //触摸结束时的处理
    div1.addEventListener("touchend", function() {
       div1.style.top = 0 + "px"
      document.removeEventListener("touchmove", defaultEvent);
    },{ passive: false });
    //阻止默认事件
    function defaultEvent(e) {
      e.preventDefault();
    }
  },

  data() {
    return {};
  }
};
</script>



<style scoped lang='scss'>
.main {
  #div1 {
    position: absolute;
    width: 200px;
    height: 200px;
    overflow: hidden;
    padding: 4px;
    border: solid 4px #59f182;
    transition: all .5s Ease;
  }
  #box  {
    width: 100%;
  }
}
</style>
